import React, { useState, useEffect } from 'react'; 
import { useHistory } from "react-router-dom";
import http from '../../../model/http';
import code from "../../../model/code";
import './billingPage.less';
import '../../../libs/font/iconfont.css'

import {  Button, List, Picker, Toast, InputItem, Modal } from 'antd-mobile';
import Header from '../../../components/header/Header'
const Item = List.Item;

function BillingPage() {
    const history = useHistory();
    const [userInfo, setUserInfo] = useState([])
    const [userData, setUserData] = useState([])
    const [mark, setMark] = useState('')

    // 总价
    const [toastPrice, setToastPrice] = useState(0)
    //抵扣金额
    const [deductionPrice,setDeductionPrice] = useState(0)
    // 本地的项目
    const [projectData, setProjectData] = useState([])

    // 顶部类型下拉菜单
    const [typeSelectData, setTypeSelectData] = useState([])
    // 下拉的值
    const [typeSelectVal, setTypeSelectVal] = useState([-1])


    // 开单人/销售员 下拉菜单
    const [salesperson, setSalesperson] = useState([])
    // 下拉的值
    const [currentSalesperson, setCurrentSalesperson] = useState([-1])


    const [consultCondition ,setConsultCondition] = useState("")

    
     
    useEffect(async () => {

        const userInfoDetail = sessionStorage.getItem('userInfoDetail') ? JSON.parse(sessionStorage.getItem('userInfoDetail')) : []
        setUserInfo(userInfoDetail)

        userDataFunc(userInfoDetail.customerCrmId) 

        //获取开单人/销售员
        getSaleperson()

        const project = localStorage.getItem('billingCartData') ? JSON.parse(localStorage.getItem('billingCartData')) : []
        let newData = []
        project.map(item => {
            newData.push(
                // useintegral 使用积分
                // actualQuotation 实际报价
                // messageComm 备注 
                Object.assign(item,{actualQuotation:'',useintegral:'',messageComm:''})
            )
        })
        console.log(newData)
        setProjectData(newData)
    }, [])

    const userDataFunc = async (userid) => {
        const result = await http.post('/order/kdInfoInit', {
            customerCrmId: userid
        })
        if (result.code == 0) {
            setUserData(result.data[0])

            let resultTypeData = result.consultType.map(item => {
                return {
                    label: item.name,
                    value: item.erp_id
                }
            })
            setTypeSelectData(resultTypeData)
        }
    }

    const getSaleperson =async ()=>{
        // http://wxwork.gzsg.cn/wxwork/order/getKDManagerList?hosId=1&userId=LiHao&managerId=1000127

        const result = await http.post('/order/getKDManagerList')
        if (result.code == 0) {
            let list =[]
            result.data.forEach(item => {
                let obj={}
                obj.label = item.user_name  + "("+item.account+")"
                obj.value = item.managerId
                // obj.account= item.account
                list.push(obj)
            })
            console.log("开单人列表",list)
            setSalesperson(list)
            setCurrentSalesperson([list[0].value ])
        }

    }
    
    

    // 开单
    const onSubmit = async () => {
        console.log(projectData)
        let boolData = projectData.find(item => {
            return item.actualQuotation == ''
        })
        console.log(boolData)
        if(boolData != undefined){Toast.fail('项目的实际报价不能为空!!');return}
        if(toastPrice - deductionPrice < 0){Toast.fail('抵扣的金额无法超过需支付的金额，请重新输入');return }
        if (typeSelectVal[0] < 0) { Toast.fail('请选择咨询类型'); return };

        
        // 项目原价
        let orderPrice = 0
        projectData.map(item => { 
            orderPrice = orderPrice + Number(item.price!=undefined?Number(item.price !=''?item.price:0):Number(item.original_price!=''?item.original_price:0)) 
        })
        
         


        Modal.alert('是否确认开单', 
            <div> 
                <div className="billing-page-model-box"><span>顾客卡号：</span><p>{userInfo.mzcode}</p></div>
                <div className="billing-page-model-box"><span>顾客名称：</span><p>{userInfo.customerName}</p></div>
                <div className="billing-page-model-box"><span>项目原价：</span><p>{orderPrice.toFixed(2)}</p></div>
                <div className="billing-page-model-box2">
                    <span>所选项目：</span> 
                </div>
                <div className="billing-page-model-box3">
                    {projectData.map(item => ( 
                        <p>{item.name} - {item.strpperCount} <br/></p> 
                    ))} 
                </div>
                <div className="billing-page-model-box"><span>项目总价：</span><p>{toastPrice.toFixed(2)}</p></div>
                <div className="billing-page-model-box"><span>可抵扣金：</span><p>{deductionPrice.toFixed(2)}</p></div>
                <div className="billing-page-model-box"><span>所需支付：</span><p style={{color:'red'}}>{(toastPrice - deductionPrice).toFixed(2)}</p></div>
            </div>
        , [
            { text: '取消' },
            {
              text: '确定', onPress: async () => {
                let projectSendData = projectData.map(item => {
                    return {
                        times: item.strpperCount,  // 个数
                        all_baojia: item.actualQuotation, // 报价
                        memo: item.messageComm, // 备注
                        use_points: item.useintegral ? item.useintegral : 0, // 使用积分
                        id: item.id,
                        type: item.itemType,  // tabs 类型
                        basic_unit: item.itemType == 2 ? item.basic_unit : '', // 产品的 
                        spec: item.itemType == 2 ? item.spec : '', // 产品的
                        activity_id: item.itemType == 4 ? item.activity_id : '' // 活动的
                    }
                })
        
                let sendData = {
                    real_need_pay_money: toastPrice - deductionPrice,   // 实际支付金额
                    customerCrmId: userInfo.customerCrmId,   // 顾客id
                    consult_type_id: typeSelectVal[0],  //咨询的类型 

                    managerId:currentSalesperson[0], //开单人/销售员
                    sum_use_points: deductionPrice,  // 总使用的积分
                    sum_baojia: toastPrice,   // 总价格 所有的报价和
                    data: projectSendData,
                    consult_condition:consultCondition //咨询情况
                    
                } 
        
                const result = await http.post_json('/order/subitem',sendData)
                console.log(result)
                if(result.code == 0){
                    Toast.success(result.msg)
                    history.push('/billingPage/success',{
                        data:sendData,
                        userInfo: userInfo,
                        projectData: projectData,
                        msg: result.msg,
                        kdtime:'',
                        money:'',
                        orderQRCode:result.orderQRCode,
                        shareUrl:result.shareurl
                    })
                    localStorage.removeItem('billingCartData')
                    localStorage.removeItem('billingCartDataID')
        
                }else{
                    Toast.fail(result.msg)
                }

              }
            }
        ])


        

       
    }


    // 购物车移除单条数据
    const oneRemoveCart = (data) => {

        Modal.alert('提示', '是否确认移除当前项目', [
            { text: '取消' },
            {
              text: '确定', onPress: async () => {
                if(projectData.length < 2){
                    Toast.fail('开单项目不能少于一条');
                    return false
                }
                
                let newLocalData = projectData.filter(item => {
                    return item.id != data.id
                })
                localStorage.setItem('billingCartData',JSON.stringify(newLocalData))
 
                setProjectData(newLocalData)

                

                // 重新赋值暂存id
                let localDataID = []
                let count = 0
                let priceData = 0
                newLocalData.map(item => {
                    localDataID.push(item.id)
                    count+= Number(item.actualQuotation)
                    priceData = priceData+Number(item.useintegral)
                })
                localStorage.setItem('billingCartDataID',JSON.stringify(localDataID)) 
 
                setToastPrice(count)
   
                // 抵扣积分金额
                setDeductionPrice(priceData)
                
              }
            }
        ])
        
    }

    // 积分
    const useintegralChange = (v,idex) => { 
        projectData[idex].useintegral = v
       
        setProjectData([...projectData]) 
        let priceData = 0
 
        projectData.map(item => {
            priceData = priceData+Number(item.useintegral) 
        })
         console.log(priceData)
        if(priceData>Number(userData.jf_amt)){
            Toast.fail('可用积分不足')
            projectData[idex].useintegral = Number(userData.jf_amt) - priceData + Number(v)

            // 抵扣积分金额
            setDeductionPrice(Number(userData.jf_amt))
        }else{
            projectData[idex].useintegral = v

            // 抵扣积分金额
            setDeductionPrice(priceData)
        } 



        
    }

    // 数量
    const strpperCountChange = (v,index) => {
        projectData[index].strpperCount = v
        setProjectData([...projectData]) 
    }
    // 
    const strpperCountBlur = (v,index) => { 
        if(v == 0){
            console.log('触发')
            projectData[index].strpperCount = 1
            setProjectData([...projectData]) 
        }
        
    }

    // 点击下拉
    const getTypeSelectVal = (v) => {
        console.log(v)
        setTypeSelectVal(v)
    }
    
    const getCurrentSalesperson =(v)=>{
        console.log(v)
        setCurrentSalesperson(v)
    }



    const amount = (v) => {
        var regStrs = [
            ['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上，但首位为0
            ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点
            ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点
            ['^(\\d+\\.\\d{2}).+', '$1'] //禁止录入小数点后两位以上
        ];
        for (let i = 0; i < regStrs.length; i++) {
            var reg = new RegExp(regStrs[i][0]);
            v = v.replace(reg, regStrs[i][1]);
        }
        return v;
    } 
    return (
        <div>
            <div className="v-billing-page">

                <div className="hearder-box">
                    <Picker data={typeSelectData} cols={1}
                        value={typeSelectVal}
                        onOk={v => getTypeSelectVal(v)}
                    >
                        <Item arrow="horizontal">咨询类型</Item>
                    </Picker>
                    <ul>
                        <li>
                            <span>顾客姓名</span>
                            <p>{userInfo.customerName}</p>
                        </li>
                        <li>
                            <span>顾客卡号</span>
                            <p>{userInfo.mzcode}</p>
                        </li>
                        <li>
                            <span>卡余额</span>
                            <p>{userData.yc_amt}</p>
                        </li>
                        <li>
                            <span>可用积分</span>
                            <p>{userData.jf_amt}</p>
                        </li>
                        <li>
                            <span>增值金余额</span>
                            <p>{userData.good_amt}</p>
                        </li>
                        <li>
                            <span>所属咨询</span>
                            <p>{userInfo.xcname}</p>
                        </li>

                    </ul>

                    <Picker data={salesperson} cols={1}
                        value={currentSalesperson}
                        onOk={v => getCurrentSalesperson(v) }
                    >
                        <Item arrow="horizontal">开单人/销售员</Item>
                    </Picker>

                </div> 
                {projectData.map((item,index) => (
                    
                    <div className="content-box">
                        <div className="content-box-header">
                            <span className="iconfont icon-wodedingdan2"></span>
                            <p>开单项目{index+1}：</p>
                            <span className="iconfont icon-shanchu" onClick={() => oneRemoveCart(item)}></span>
                            <div className="clear"></div>
                        </div>
                        <ul>
                            <li>
                                <span>项目名称</span>
                                <p>{item.name}</p>
                            </li>
                            <li>
                                <span>购买数量</span>
                                <InputItem type='number'   
                                    value={item.strpperCount}  
                                    onChange={(v) => strpperCountChange(v,index)} 
                                    className="input-box" 
                                    onBlur={(v => strpperCountBlur(v,index))}
                                /> 
                            </li>
                            <li>
                                <span>使用次数</span>
                                <p>{item.use_times?item.use_times:1}</p>
                            </li>
                            <li>
                                <span>总次数</span>
                                <p>{item.strpperCount * (item.use_times?item.use_times:1)}</p>
                            </li>
                            <li>
                                <span>项目原价</span>
                                <p>{item.price!=undefined?item.price:item.original_price}</p>
                            </li>
                            {item.activity_price ? <li>
                                <span>活动价</span>
                                <p>{item.activity_price}</p>
                            </li>:''}
                            
                            <li>
                                <span style={{position:'relative'}}>实际报价 <b style={{color:'#d22c4a',position:'absolute',top:'-4px',right:'-13px',display:'block'}}>*</b></span>
                                <InputItem type='money' value={item.actualQuotation}  onChange={(v) => {
                                    item.actualQuotation = amount(v)
                                    let count = 0
                                    projectData.map(data => {
                                        count+= Number(data.actualQuotation)
                                    })
                                    setProjectData([...projectData])
                                    setToastPrice(count)
                                }} className="input-box " min="1" /> 
                            </li>
                            <li>
                                <span>使用积分</span>
                                
                                <InputItem type='number' max={20} placeholder="0" value={item.useintegral}  onChange={(v) => useintegralChange(v,index)
                                    
                                } className="input-box inputNameBox" min="1" />
                               
                            </li> 
                        </ul> 
                        <textarea className="box-textarea" placeholder='请填写您的备注...' onChange={(e)=>{item.messageComm = e.target.value }} defaultValue={item.messageComm} ></textarea>
                   
                        {/* <textarea className="box-textarea" placeholder='咨询情况,非必填' onChange={(e)=>{item.consult_condition = e.target.value }} defaultValue={item.consult_condition} ></textarea> */}
                   
                   
                    </div>
                ))} 


                {
                  projectData.length > 0 ? (
                    <div className="content-box">
                    <textarea className="box-textarea" placeholder='咨询情况,非必填' onChange={(e)=>{ setConsultCondition(e.target.value)  }} defaultValue={consultCondition} ></textarea>
                     </div>
                  ) : null

                }
               
              
                
                <div className="price-count">
                    <span>共{projectData.length}项目</span>
                    <p>需支付：<b>{(toastPrice - deductionPrice).toFixed(2)}</b></p>
                </div>
                <div className="price-count">
                    <span>总计：<b style={{color:'#d22c4a'}}>{toastPrice.toFixed(2)}</b></span>
                    <p>抵扣金额：<b>{deductionPrice.toFixed(2)}</b></p>
                </div>
                <Button type="warning" className="btn-class" onClick={() => onSubmit()}>确认开单</Button>
               
            </div>

            


            <Header />
        </div>
    )
}
export default BillingPage;


// jf_amt  // 积分、
// consultname 所属咨询
// card_no：卡号
// good_amt 增值金

// yc_amt 卡余额